#include "internet_police.h"


Internet_Police::Internet_Police(QObject *parent) :
        QObject(parent)
{    
    this->internetManager = new QNetworkAccessManager(this);
    //
    // connette lo slot per la ricezione da internet:
    connect(this->internetManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
}


void Internet_Police::finished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QString buffer = QString(reply->readAll());

        qDebug(buffer.toAscii().constData());
        if (buffer.contains("non risulta")) { // auto non rubata
            emit vehicleValid();
        }
        else {
            QString         tmp;
            QVariantList    modelReturned;

            //ui->lblTargaOttenuta->setText(ui->txtPlate->text().toUpper());
            buffer = buffer.mid(buffer.indexOf(plate) + plate.length()); // si posiziona dopo la targa
            tmp = buffer.mid(buffer.indexOf("Telaio"));
            tmp = tmp.mid(tmp.indexOf("#FF0000'>") + 9);
            buffer = buffer.mid(buffer.indexOf("#FF0000'>") + 9);
            modelReturned.append(tmp.mid(0, tmp.indexOf("</"))); // prende il telaio

            tmp = buffer.mid(buffer.indexOf("Modello"));
            tmp = tmp.mid(tmp.indexOf("#FF0000'>") + 9);
            buffer = buffer.mid(buffer.indexOf("#FF0000'>") + 9);
            modelReturned.append(tmp.mid(0, tmp.indexOf("</"))); // prende il modello

            tmp = buffer.mid(buffer.indexOf("Fabbrica"));
            tmp = tmp.mid(tmp.indexOf("#FF0000'>") + 9);
            buffer = buffer.mid(buffer.indexOf("#FF0000'>") + 9);
            modelReturned.append(tmp.mid(0, tmp.indexOf("</"))); // prende la fabbrica

            tmp = buffer.mid(buffer.indexOf("Tipo"));
            tmp = tmp.mid(tmp.indexOf("#FF0000'>") + 9);
            buffer = buffer.mid(buffer.indexOf("#FF0000'>") + 9);
            modelReturned.append(tmp.mid(0, tmp.indexOf("</"))); // prende il tipo

            buffer = buffer.mid(buffer.indexOf("#FF0000'>") + 9);
            tmp = buffer.mid(buffer.indexOf("<p"));
            tmp = tmp.mid(0, tmp.indexOf("</p>") + 4);
            tmp = tmp.replace("size=\"5\"", "size=\"2\"");
            modelReturned.append(tmp); // prende le note
            emit searchCompleted(modelReturned);
        }
    }
    else
        ; // informa che non � possibile collegarsi online per la verifica delle informazioni
    reply->deleteLater();
}


Internet_Police::~Internet_Police()
{
}

void Internet_Police::on_cmdSend_clicked(QString plate)
{    
    this->plate = plate;
    this->internetManager->get(QNetworkRequest(QUrl(QString(URL_REQUEST) + "NumeroTarga=" + plate.trimmed() + "&NumeroTelaio=")));
}

